"""角色管理器"""

from src.db import dbm, dbs
from src.utils.deep import get_os_info
from src.core.variables.status import *
from src.core.variables.function import *
from src.core.variables.exception import *


def add_role(schema, user):
    """添加角色"""
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        now = get_os_info.local_time("continuous")
        temp = {
            "uid": CREATE_ID(),
            "name": schema.name,
            "description": schema.description,
            "status": schema.status,
            "create_time": now,
            "create_user": user.username,
            "update_time": now,
            "update_user": user.username,
        }
        db_session.add(dbs.sys_default.Role(**temp))
        if dbm.commit(db_session):
            return SUCCESS_CODE_CUSTOMIZE("添加成功！")
        raise MAIN_EXCEPTION(f"提交数据库更改失败！")


def remove_role(schema):
    """移除角色"""
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.Role)
            .filter(dbs.Role.role_id == schema.role_id)
            .first()
        )
        if db_result:
            db_session.delete(db_result)
        else:
            raise MAIN_EXCEPTION(f"角色不存在！")
        if dbm.commit(db_session):
            return SUCCESS_CODE_CUSTOMIZE("删除成功！")
        raise MAIN_EXCEPTION(f"提交数据库更改失败！")


def update_role(schema):
    """更新角色"""
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.Role)
            .filter(dbs.Role.role_id == schema.role_id)
            .first()
        )
        if db_result:
            db_result.name = schema.name
            db_result.description = schema.description
            db_result.status = schema.status
            db_result.update_time = get_os_info.local_time("continuous")
            db_result.update_user = schema.update_user
        else:
            raise MAIN_EXCEPTION(f"角色不存在！")
        if dbm.commit(db_session):
            return SUCCESS_CODE_CUSTOMIZE("更新成功！")
        raise MAIN_EXCEPTION(f"提交数据库更改失败！")
